// pages/home-music/index.js
import { rankingStore, rankingMap, playerStore } from "../../store/index"

import {getBanners, getSongMenu} from "../../server/api_music"
import queryRect from "../../utils/query-rect"
import throttle from "../../utils/throttle"

const throttleOueryRect = throttle(queryRect, 500, { trailing: true})
Page({
    data: {
        // 设置图片的高度
        swiperHeight: 0,
        banners: [],
        hotSongMenu: [],
        recommendSongMENU: [],
        recommendSongMenu: [],
        // 推荐歌曲
        recommendSongs: [],
        rankings: {0: {}, 2: {}, 3: {}},

        currentSong: {},
        isplaying: false,
        playAnimState: "paused",

        currentLyricText: ""
    },
    onLoad: function (options) {
       this.getpalyData()

        // 发起共享请求
        rankingStore.dispatch("getRankingDataAction")
        // 从store获取共享的数据
        this.setupPlayerStoreListener()

    },

    // 网络请求
    getpalyData() {
        getBanners().then(res => {
            this.setData({ banners: res.banners })
         })

         getSongMenu().then(res => {
            this.setData({ hotSongMenu: res.playlists })
         })

         getSongMenu("华语").then(res => {
            this.setData({ recommendSongMenu: res.playlists })
         })
    },


    // 事件处理
    // 点击输入款跳转到detail-search页面
    handleSearchClick() {
       wx.navigateTo({
         url: '../detail-search/index',
       })
    },

    handleMoreClick() {
        this.navigateToDetailSongsPage("hotRanking")
    },

    handleRankingItemClick(event) {
        const idx = event.currentTarget.dataset.idx
        const  rankingName = rankingMap[idx]
        this.navigateToDetailSongsPage(rankingName)
    },

navigateToDetailSongsPage: function(rangkingName) {
    wx.navigateTo({
        url: `../detail-songs/index?ranking=${rangkingName}&type=rank`,
      })
},
    // 监听图片加载完成
handleSwieprImageLoaded() {
    //获取图片的高度
    throttleOueryRect(".swiper-image").then(res => {
        const rect = res[0]
        this.setData({swiperHeight:  rect.height})
    })

},

handleSongItemClick: function(event) {
    const index = event.currentTarget.dataset.index
    playerStore.setState( "palyListSongs", this.data.recommendSongs)
    playerStore.setState("playListIndex", index)
},

onUnload: function() {},
    
setupPlayerStoreListener: function() {
        // 从store获取共享的数据
    rankingStore.onState("hotRanking", (res) => {
        if(!res.tracks) return 
        const recommendSongs = res.tracks.slice(0, 6)
        this.setData({ recommendSongs })
    })
    rankingStore.onState("newRanking", this.getRankingHandler(0))
    rankingStore.onState("originRanking", this.getRankingHandler(2))
    rankingStore.onState("upReanking", this.getRankingHandler(3))
    // 播放器监听
    playerStore.onStates(["currentSong", "isPlaying", "currentLyricText"],  ({currentSong, isPlaying, currentLyricText}) => {
        if(currentSong) this.setData({ currentSong })
        if(isPlaying !== undefined) {
            this.setData({ 
                    isPlaying, 
                    playAnimState: isPlaying ? "runing" : "paused" })
        }
        if(currentLyricText !== undefined) this.setData({ currentLyricText })
    })
},

getRankingHandler: function(idx) {
    return (res) => {
        if(Object.keys(res).length === 0) return
        const name = res.name
        const coverImgUrl = res.coverImgUrl
        const playCount = res.playCount
        const songList = res.tracks.slice(0, 3)
        const rankingObje = {name, coverImgUrl, playCount, songList}
        const newRankings = {...this.data.rankings, [idx]: rankingObje}
        this.setData({
            rankings: newRankings
        })
    }
  },

//   暂停和播放
handlePlayBtnClick: function() {
    playerStore.dispatch("changeMusicPlayStatusAction", !this.data.isPlaying)
}, 

// 跳转到detail-play页面
handlePlayBarClick: function() {
    wx.navigateTo({
      url: '/pages/music-player/index',
    })
}
})